package lims.client;




import javax.print.DocFlavor;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.JOptionPane;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.KeyStroke;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import java.awt.event.KeyEvent;
import java.awt.event.InputEvent;

import javax.swing.JPanel;

import java.awt.BorderLayout;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.border.BevelBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.TableModel;
import javax.swing.ListSelectionModel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;

import lims.bridge.remoteprint.Main;
import lims.client.LimsService;


@Service
public class MainFrame extends JFrame{
	private static Log logger=LogFactory.getLog(MainFrame.class);
	
	private LimsService limsService;
	
//	private PrinterMessageService printerMessageService;
	
	private JLabel statusBar=null; 
	public void setLimsService(LimsService limsService) {
		this.limsService = limsService;
	}

	private JTabbedPane tabbedPane=null;		
	public void setStatus(String status){
		statusBar.setText(status);
	}
	
	public DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE; 
	
	public PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet(); 
				    				
	public PrintService printService = PrintServiceLookup.lookupDefaultPrintService();

	
	
	public MainFrame() {		
		
		setSize(800,600);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		
		JMenu mnNewMenu = new JMenu("系统");
		menuBar.add(mnNewMenu);
				
		JMenuItem mntmNewMenuItem_2 = new JMenuItem("退出");
		mntmNewMenuItem_2.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.ALT_MASK));
		mntmNewMenuItem_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				MainFrame.this.dispose();
			}
		});
		
		JMenuItem mntmNewMenuItem = new JMenuItem("设置");
		mntmNewMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				doConfig();
			}
		});
		mnNewMenu.add(mntmNewMenuItem);
		
		JMenuItem mntmNewMenuItem_5 = new JMenuItem("登录");
		mntmNewMenuItem_5.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				doLogin();
			}
		});
		mnNewMenu.add(mntmNewMenuItem_5);
		
		JMenuItem mntmNewMenuItem_3 = new JMenuItem("保存");
		mnNewMenu.add(mntmNewMenuItem_3);
		mntmNewMenuItem_3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					Main.writeUserConfig();
					JOptionPane.showMessageDialog(MainFrame.this,"保存成功");
				} catch (Exception e1) {
					e1.printStackTrace();
					JOptionPane.showMessageDialog(MainFrame.this,e1.getMessage());
				}
			}
		});
		mntmNewMenuItem_3.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.ALT_MASK));
		mnNewMenu.add(mntmNewMenuItem_2);
		
		JMenu mnNewMenu_2 = new JMenu("输出设备");
		menuBar.add(mnNewMenu_2);
		
		JMenuItem menuItem = new JMenuItem("添加");
		menuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				doAddPrinter();
			}
		});
		mnNewMenu_2.add(menuItem);
		
		JMenuItem mntmNewMenuItem_1 = new JMenuItem("修改");
		mntmNewMenuItem_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				doEditPrinter();
			}
		});
		mnNewMenu_2.add(mntmNewMenuItem_1);
		
		JMenuItem mntmNewMenuItem_4 = new JMenuItem("删除");
		mntmNewMenuItem_4.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				doRemovePrinter();
			}
		});
		mnNewMenu_2.add(mntmNewMenuItem_4);
		
		JPanel panel = new JPanel();
		panel.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
		getContentPane().add(panel, BorderLayout.SOUTH);
		panel.setLayout(new BorderLayout(0, 0));
		
		statusBar = new JLabel(".");
		statusBar.setHorizontalAlignment(SwingConstants.LEFT);
		panel.add(statusBar);
		
		
		
		tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		getContentPane().add(tabbedPane, BorderLayout.CENTER);
		
		JSplitPane splitPane = new JSplitPane();
		splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
		splitPane.setDividerLocation(100);
		tabbedPane.addTab("输出设备", null, splitPane, null);
		
		JScrollPane scrollPane_1 = new JScrollPane();
		splitPane.setLeftComponent(scrollPane_1);
		
		table_devicelist = new JTable();
		table_devicelist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table_devicelist.setModel(DeviceTableModel.getInstance());
		scrollPane_1.setViewportView(table_devicelist);
		
		JScrollPane scrollPane_2 = new JScrollPane();
		splitPane.setRightComponent(scrollPane_2);
		
		table_joblist = new JTable();
		table_joblist.setModel(new JobTableModel());
		scrollPane_2.setViewportView(table_joblist);
	}

	protected void doConfig() {
		ConfigDialog dlg=new ConfigDialog();
		dlg.loadConfig();
		dlg.setModal(true);
		dlg.setVisible(true);
		if(dlg.modalResult)	dlg.updateConfig();
		limsService=new Main().initializeLimsService();
	}

	protected void doLogin() {
		
		try{
			limsService.initHttpClient();
			boolean loggedIn=limsService.login(limsService.getUid(),limsService.getPwd());
			limsService.closeHttpClient();
			if(loggedIn){
				setStatus(String.format("当前用户:%s",limsService.userName));
				JOptionPane.showMessageDialog(MainFrame.this,"登录成功");
			}else{
				JOptionPane.showMessageDialog(MainFrame.this,"登录不成功");
			}
		}catch(Exception e){
			e.printStackTrace();
			JOptionPane.showMessageDialog(MainFrame.this,e.getMessage());
		}
		

	}

	protected void doRemovePrinter() {
		int index=table_devicelist.getSelectedRow();
		if(index<0){
			JOptionPane.showMessageDialog(this,"请选择打印设备");
			return;		
		}
		DeviceTableModel model=(DeviceTableModel) table_devicelist.getModel();
		if(JOptionPane.showConfirmDialog(this,"将要删除所选打印设备，是否继续","警告",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
			model.remove(index);
			model.afterChange();	    			
		}
	}

	protected void doEditPrinter() {
		int index=table_devicelist.getSelectedRow();
		if(index<0){
			JOptionPane.showMessageDialog(this,"请选择打印设备");
			return;		
		}
		
		DeviceTableModel model=(DeviceTableModel) table_devicelist.getModel();
		LimsPrinter printer=model.get(index);
		DialogPrinter dlg=new DialogPrinter(printer,this);
		dlg.setModal(true);
		dlg.setLocationByPlatform(true);
		dlg.setVisible(true);
		if(dlg.modalResult){
	    	model.afterChange();
	    }
	}

	protected void doAddPrinter() {
	    LimsPrinter printer=new LimsPrinter();
	    try{
	    if(printer.setUp()){
	    	DeviceTableModel model=(DeviceTableModel) table_devicelist.getModel();
	    	model.add(printer);
	    	model.afterChange();
	    }}catch(Exception e){
	    	JOptionPane.showMessageDialog(this,e.getMessage());	    	
	    }
	}

	
	public DialogPrint dlgPrint=null;
	

	public class JobTableModel extends Vector<Vector<Object>> implements TableModel{
		/**
		 * 
		 */
		private static final long serialVersionUID = -5353218577001443692L;
		private Vector<String> headers=new Vector<String>();
		private List<TableModelListener> listeners=new ArrayList<TableModelListener>();
		public JobTableModel(){
			super();
			headers.add("用户");
			headers.add("文档名称");
			headers.add("设备");
			headers.add("输出时间");
			headers.add("输出类型");
			headers.add("页数");
		}
		
		@Override
		public int getRowCount() {			
			return size();
		}

		@Override
		public int getColumnCount() {			
			return headers.size();
		}

		@Override
		public String getColumnName(int columnIndex) {
			return headers.get(columnIndex);
		}

		@Override
		public Class<?> getColumnClass(int columnIndex) {
			return String.class;
		}

		@Override
		public boolean isCellEditable(int rowIndex, int columnIndex) {
			return false;
		}

		@Override
		public Object getValueAt(int rowIndex, int columnIndex) {		
			Vector<Object> row=get(rowIndex);
			if(row==null) return null;
			return row.get(columnIndex);
		}

		@Override
		public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
			Vector<Object> row;
			if(rowIndex>=size()) {
				setSize(rowIndex+1);
				row=new Vector<Object>(headers.size());
				set(rowIndex, row);
			}else row=get(rowIndex);
			row.set(columnIndex, aValue);			
		}
		
		public void afterChange(){
			for(TableModelListener l:listeners){
				l.tableChanged(new TableModelEvent(this));
			}
		}

		@Override
		public void addTableModelListener(TableModelListener l) {
			if(listeners.contains(l)) return;
			listeners.add(l);
		}

		@Override
		public void removeTableModelListener(TableModelListener l) {
			if(!listeners.contains(l)) return;
			listeners.remove(l);
		}
		
	}
	/**
	 * 
	 */
	private static final long serialVersionUID = 6039681006865630008L;
	private JTable table_devicelist;
	private JTable table_joblist;

	
}
